package ch09;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;

public class MessageDAO4 {

	private JdbcRowSet rowSet;
	
	public MessageDAO4(String url,String user,String passwd) throws SQLException{
		rowSet = RowSetProvider.newFactory().createJdbcRowSet();
		
		rowSet.setUrl(url);
		rowSet.setUsername(user);
		rowSet.setPassword(passwd);
		rowSet.setCommand("SELECT * FROM t_message");
		rowSet.execute();
		
	}
	
	public void add(Message message) throws SQLException {
		rowSet.moveToCurrentRow();
		rowSet.updateString(2, message.getName());
		rowSet.updateString(3, message.getEmail());
		rowSet.updateString(4, message.getMsg());
		rowSet.insertRow();
	}
	
	public List<Message> get() throws SQLException{
		List<Message> messages = new ArrayList<>();
		
		rowSet.beforeFirst();
		
		while(rowSet.next()){
			Message message = toMessage();
			messages.add(message);
		}
		
		return messages;
	}

	private Message toMessage() throws SQLException {
		Message message = new Message();
		message.setId(rowSet.getLong(1));
		message.setName(rowSet.getString(2));
		message.setEmail(rowSet.getString(3));
		message.setMsg(rowSet.getString(4));
		return message;
	}
	
	public void close() throws SQLException{
		if(rowSet != null){
			rowSet.close();
		}
	}
}
